<?php
/**
 * Created by PhpStorm.
 * User: DongYao
 * Date: 2018/1/26
 * Time: 下午5:28
 */

namespace App\Support\MobileSms;


use App\Tables\MobileSms;
use Carbon\Carbon;

class Sms implements SmsInterface
{

    /**
     * 生成手机短信息
     * @param string $mobile
     * @param string $content
     * @param string $content_type
     * @return mixed
     */
    public function makeSms(string $mobile, string $content, string $content_type)
    {
        return MobileSms::create([
            'type' => 'sms',
            'mobile' => $mobile,
            'content' => $content,
            'content_type' => $content_type,
        ]);
    }

    /**
     * 生成手机验证码
     * @param string $mobile
     * @param string $code
     * @param string $content
     * @param string $content_type
     * @param int $user_platform
     * @return mixed
     */
    public function makeAuthCode(string $mobile, string $code, string $content, string $content_type, int $user_platform = self::USER_PLATFORM_FRONT)
    {
        return MobileSms::create([
            'type' => 'auth_code',
            'platform' => $user_platform,
            'mobile' => $mobile,
            'code' => $code,
            'content' => $content,
            'content_type' => $content_type,
        ]);
    }

    /**
     * 验证手机验证码
     * @param string $mobile
     * @param string $code
     * @param int $ttl
     * @param int $user_platform
     * @return mixed
     */
    public function verifyAuthCode(string $mobile, string $code, int $ttl = 600, int $user_platform = self::USER_PLATFORM_FRONT)
    {
        // 发送时间 + ttl >= 当前时间 有效
        $sms = MobileSms::where('mobile', $mobile)
            ->where('type', 'auth_code')
            ->where('platform', $user_platform)
            ->where('code', $code)
            ->where('updated_at', '>=', Carbon::now()->subSecond($ttl))
            ->first();

        if (empty($sms)) {
            return '无效的验证码';
        }

        if ($sms->is_used == 1) {
            return '验证码已使用';
        }

        $sms->is_used = 1;
        $sms->save();

        return true;
    }
}